package cn.edu.scnu.service;

import cn.edu.scnu.entity.PlaybackHistory;
import cn.edu.scnu.mapper.PlaybackHistoryMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class PlaybackHistoryService extends ServiceImpl<PlaybackHistoryMapper, PlaybackHistory> {
    @Autowired
    private PlaybackHistoryMapper playbackHistoryMapper;

    // 展示用户观看记录
    public List<PlaybackHistory> showPlaybackHistory(String phone) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        List<PlaybackHistory> playbackHistoryList = playbackHistoryMapper.selectList(queryWrapper);
        return playbackHistoryList;
    }

    // 新增用户观看记录
    public void addPlaybackHistory(String phone, Integer movieId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("movie_id", movieId);
        PlaybackHistory playbackHistory = new PlaybackHistory();
        playbackHistory.setPhone(phone);
        playbackHistory.setMovieId(movieId);
        LocalDateTime time = LocalDateTime.now();
        playbackHistory.setViewingTimestamp(Timestamp.valueOf(time));
        // 该用户没播放过此电影，则新增记录
        if (playbackHistoryMapper.selectList(queryWrapper).size() == 0) {
            playbackHistoryMapper.insert(playbackHistory);
        }
        else {
            playbackHistoryMapper.updateById(playbackHistory);
        }
    }

}
